<?php
namespace app\api\controller;

use app\common\controller\Api;
use addons\litestore\model\Litestoreorder;
use think\Db;

/**
 * Stripe苹果支付接口
 * Class ApplePay
 * @package app\api\controller
 */
class StripePay extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

//    protected $stripeSecretKey = 'sk_test_51MwfTxJbL7V1IbvnjBaC6AAlYe2QAe5gQfqbGUA4AapYbtxfeAUk2qvpWW7fCwwa3jGT8WnXJLpVMvQNMqfNdF5X00NUwAGFAo';//测试
//    protected $endpoint_secret = 'whsec_59Qe9wQBA7aAMYVwXeT6bej34xxqnxRF';//测试

    protected $stripeSecretKey = '';
    protected $endpoint_secret = '';

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 初始化参数
     */
    public function __construct()
    {
        //从后台配置中获取账号信息
        $config = Db::name('pay_method')->where('id',2)->value('config');
        $config = json_decode($config,true);
        $this->stripeSecretKey = $config['stripeSecretKey'];
        $this->endpoint_secret = $config['endpoint_secret'];
    }

    /**
     * 付款
     */
    public function pay($order_id,$order_no,$pay_price,$desc)
    {
        require_once __DIR__.'/../../../extend/stripe-php/init.php';

        \Stripe\Stripe::setApiKey($this->stripeSecretKey);
        header('Content-Type: application/json');
        $YOUR_DOMAIN = request()->domain() .'/#/orderDetail/'.$order_id;//支付后跳转页面
        $accept_url = request()->domain().'/api.php/api/stripe_pay/callback?order_id='.$order_id;//同步回调地址
        try {
            $checkout_session = \Stripe\Checkout\Session::create([
                'line_items' => [[
                    'price_data' => [
                        'currency' => 'usd',
                        'product_data' => [
                            'name' => $desc.',单号：'.$order_no,
                        ],
                        'unit_amount' => $pay_price * 100,
                    ],
                    'quantity' => 1,
                ]],
                'mode' => 'payment',
                'payment_intent_data'=>['metadata' => ["order_id" => $order_no]],
//                'success_url' => $YOUR_DOMAIN . '?state=PaymentSucceeded',
//                'cancel_url' => $YOUR_DOMAIN . '?state=PaymentFailed',
                'success_url' => $accept_url,
                'cancel_url' => $YOUR_DOMAIN . '?state=PaymentFailed',
            ]);
            writelog('stripe_pay',$checkout_session);
        } catch (\Exception $e) {
            return ['code'=>0,'data'=>$e->getMessage()];
        }
        header("HTTP/1.1 303 See Other");
        return ['code'=>1,'data'=>$checkout_session->url];
    }

    /**
     * 回调
     */
    public function callback()
    {
        writelog('stripeCallback', $_REQUEST);

        //处理相关业务
//        $order = (new Litestoreorder())->payDetailById($_GET['order_id']);
//        if (empty($order)) { // 如果订单不存在
//            writelog('Callback',"支付成功，查询订单失败，状态未修改");
//        }
//        $order->updatePayStatus($paymentId,'paypal');

        $web_url = request()->domain() .'/#/orderDetail/'.$_GET['order_id'].'?state=PaymentSucceeded';
        header('Location: '.$web_url);
        exit();
    }

    //异步回调
    public function notify(){
        require_once __DIR__.'/../../../extend/stripe-php/init.php';
        $stripe = new \Stripe\StripeClient($this->stripeSecretKey);

        $endpoint_secret = $this->endpoint_secret;

        $payload = @file_get_contents('php://input');
        $sig_header = $_SERVER['HTTP_STRIPE_SIGNATURE'];
        $event = null;

        try {
            $event = \Stripe\Webhook::constructEvent(
                $payload, $sig_header, $endpoint_secret
            );
        } catch (\UnexpectedValueException $e) {
            // Invalid payload
            http_response_code(400);
            exit();
        } catch (\Stripe\Exception\SignatureVerificationException $e) {
            // Invalid signature
            http_response_code(400);
            exit();
        }
// Handle the event
        switch ($event->type) {
            case 'payment_intent.succeeded':
                $paymentIntent = $event->data->object;
                writelog('stripe_notify',$paymentIntent);

            // ... handle other event types
                $order_no = $paymentIntent->metadata->order_id;
                $transaction_id = $paymentIntent->id;

                //处理相关业务
                $order = (new Litestoreorder())->payDetail($order_no);
                if (empty($order)) { // 如果订单不存在
                    writelog('stripe_notify',"订单不存在");
                }
                $order->updatePayStatus($transaction_id,'stripe');
                writelog('stripe_notify',"支付成功");

            default:
                echo 'Received unknown event type ' . $event->type;
        }

        http_response_code(200);
    }
}